//
//  WBOAuthController.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/8/30.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit
import SVProgressHUD
let WB_APPKEY = "2934094384"
let WB_SECRET = "bbbafe538f5d6d9eb5bec8abc8dcdb7f"
let WB_REDIRECT_URI = "http://www.baidu.com/"
class WBOAuthController: UIViewController,UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
    }
    private func setUI()
    {
        view.backgroundColor = UIColor.white
        title = "新浪微博-登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "取消", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, action: #selector(autoFill))
        
        self.view.addSubview(webView)
        //设置webview的约束
        webView.snp_makeConstraints { (make)->Void in
            make.edges.equalTo(self.view)
        }
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = URL(string: urlString)!
        let request = NSURLRequest(url: url)
        webView.loadRequest(request as URLRequest)
    }
    func autoFill()
    {
        let jsString = "document.getElementById('userId').value = 'bzy0527@163.com';document.getElementById('passwd').value = 'aaa888';"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    @objc private func close()
    {
        dismiss(animated: true, completion: nil)
    }
    //懒加载webview
    lazy var webView : UIWebView = {
        let webview = UIWebView()
        webview.delegate = self
        return webview
    }()
    
    /*
    // MARK: - 私有方法
    private func loadAccessToken(code:String)
    {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id": WB_APPKEY,
            "client_secret": WB_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URI
        ]
        //使用afn发起POST请求
        WBNetworkTools.sharedTools.request(method: .Post, urlString: urlString, parameters: parameters) { (responce, error) in
            if responce == nil || error != nil {
                print("请求错误\(error)")
                return
            }else
            {
                //print(responce!)
                let account = WBUserAccount(dick: responce! as! [String : Any])
                //
                self.loadUserInfo(account: account)
            }
            
        }
    }
    
    //获取用户的个人信息
    private func loadUserInfo(account:WBUserAccount)
    {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = [
            "access_token":(account.access_token ?? ""),
            "uid": (account.uid ?? "")
        ]
        //发起请求
        WBNetworkTools.sharedTools.request(method: .Get, urlString: urlString, parameters: parameters) { (responce, error) in
            if responce == nil || error != nil
            {
                print("请求错误\(error)")
                return
            }
            //print(responce)
            let dict = responce! as! [String : Any]
            account.name = dict["name"]! as? String
            account.profile_image_url = dict["profile_image_url"]! as? String
            account.avatar_large = dict["avatar_large"]! as? String
            self.saveAccount(account: account)
        }
    }
    
    ///保存到文件路径
    private func saveAccount(account:WBUserAccount)
    {
        let file = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        // 2. 归档
        NSKeyedArchiver.archiveRootObject(account, toFile: file)
    }
    */
   // MARK: - UIWebViewDelegate
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //print(request.url)
        if let u = request.url {
            let urlString = u.absoluteString
            //print(urlString)
            if !urlString.hasPrefix(WB_REDIRECT_URI) {
                return true
            }
        }
        
        if let query = request.url?.query {
            //print(query)
            let code = query.substring(from: "code=".endIndex)
            //print(code)
            //获取到授权码
            //loadAccessToken(code: code)
            WBUserAccountViewModel.sharedModel.loadAccessToken(code: code, completion: { (isSuccess) in
                if isSuccess {
                    // 登录成功的话，需要在这个地方切换界面、
                    print("切换界面")
                    self.dismiss(animated: false, completion: { 
                        NotificationCenter.default.post(name: NSNotification.Name(WBChangeRootVCNotification), object: self)
                    })
                }else{
                    print("登录失败")
                }
            })
            
        }
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   
}
